﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Saxon.Api;
using System.Text.RegularExpressions;
using WMM.Tapioca.Linkbase;
using WMM.Tapioca.Instance;
using WMM.Tapioca.Taxonomy;

namespace WMM.Tapioca.Formula.Filters
{
    /// <summary>
    /// The period-start filter can be used to match facts based upon the start 
    /// of the duration over which they have been measured. 
    /// </summary>
    public class PeriodStartFilter : PeriodFilter
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        public PeriodStartFilter(Resource resource)
            : base(resource)
        {
            string expression = (string)resource.ResourceXElement.Attribute("date") ?? string.Empty;
            expression = expression.TrimEnd().TrimStart();
            expression = Regex.Replace(expression, @"\s+", " ");
            Date = EvaluateExpression(expression);

            string expTime = (string)resource.ResourceXElement.Attribute("time") ?? string.Empty;
            expTime = expTime.TrimEnd().TrimStart();
            expTime = Regex.Replace(expTime, @"\s+", " ");

            if (expTime != string.Empty)
            {
                Time = EvaluateExpression(expTime);
            }
            else
            {
                Time = "00:00:00";
            }
        }


        public override List<FactItem> EvaluateFilter(VariableSet variableSet, List<FactItem> itemsToFilter, DTS dts)
        {
            List<FactItem> itemListTemp = new List<FactItem>();

            DateT = DateTime.Parse(Date + " " + Time);

            foreach (FactItem item in itemsToFilter)
            {
                if (Complement ? !item.ContextRef.PeriodStartDate.Equals(DateT) : item.ContextRef.PeriodStartDate.Equals(DateT))
                {
                    itemListTemp.Add(item);
                }
            }

            return itemListTemp;
        }
    }
}
